<!-- eslint-disable vue/valid-attribute-name -->
<template>
  <el-card>
    <el-form :inline="true" class="form">
      <el-form-item label="职位搜索">
        <el-input
          placeholder="请你输入搜索职位关键字"
          v-model="keyword"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="default" @click="search">
          搜索
        </el-button>
        <el-button type="default" size="default" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px">
    <el-button type="primary" size="default" icon="Plus" @click="addRole">
      添加职位
    </el-button>
    <el-table border style="margin: 10px 0px" :data="allRole">
      <el-table-column type="index" align="center" label="#"></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column
        label="职位名称"
        align="center"
        prop="rolename"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        show-overflow-tooltip
        prop="createTime"
        :formatter="createTimeformatter"
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        show-overflow-tooltip
        prop="updateTime"
        :formatter="updateTimeformatter"
      ></el-table-column>
      <el-table-column label="操作" width="280px" align="center">
        <!-- row:已有的职位对象 -->
        <template #="{ row }">
          <el-button
            type="primary"
            size="small"
            icon="User"
            @click="setPermission(row)"
          >
            分配权限
          </el-button>
          <el-button
            type="warning"
            size="small"
            icon="Edit"
            @click="updateRole(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`你确定要删除${row.rolename}?`"
            width="260px"
            @confirm="deleteRole(row.id)"
          >
            <template #reference>
              <el-button type="danger" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="getHasRole"
      @size-change="sizeChange"
    />
  </el-card>
  <!-- 添加职位与更新已有职位的结构:对话框 -->
  <el-dialog
    v-model="dialogVisite"
    :title="RoleParams.id ? '更新职位' : '添加职位'"
  >
    <el-form ref="form" :model="RoleParams" :rules="rules">
      <el-form-item label="职位名称" prop="roleName">
        <el-input
          placeholder="请输入职位名称"
          v-model="RoleParams.roleName"
        ></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisite = false">取消</el-button>
      <el-button type="primary" @click="save">确定</el-button>
    </template>
  </el-dialog>
  <!-- 抽屉组件：分配职位的菜单权限与按钮的权限 -->
  <el-drawer v-model="drawer">
    <template #header>
      <h4>分配菜单权限</h4>
    </template>
    <template #default>
      <!-- 树形控件 -->
      <el-tree
        ref="tree"
        :data="menuArr"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="selectArr"
        :props="defaultProps"
      ></el-tree>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button type="default" size="default" @click="drawer = false">
          取消
        </el-button>
        <el-button type="primary" size="default" @click="handler">
          确定
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import {
  reqAllRoleList,
  reqAddOrUpdateRole,
  reqRemoveRole,
  reqAllMenuList,
  reqSetPermission,
} from '@/api/acl/role'
import type { Records, RoleData, MenuList } from '@/api/acl/role/type'
import useLayOutSettingStore from '@/store/modules/settings'
import { ElMessage } from 'element-plus'
import { nextTick, onMounted, reactive, ref } from 'vue'

// 当前页码
let pageNo = ref<number>(1)
// 一页展示的条数
let pageSize = ref<number>(10)
// 搜索职位关键字
let keyword = ref<string>('')
// 总条数
let total = ref<number>(0)
// 全部职位信息
let allRole = ref<Records>([])
// 弹窗是否显示
let dialogVisite = ref<boolean>(false)
// 表单对象
let form = ref<any>()
// 收集新增岗位数据
let RoleParams = reactive<RoleData>({
  roleName: '',
})
// 抽屉组件是否显示
let drawer = ref<boolean>(false)
// 存储勾选ID
let selectArr = ref<number[]>([])
// 定义数组存储用户权限的数据
let menuArr = ref<MenuList>([])
// 获取tree组件实例
let tree = ref<any>()
// 默认的树形控件属性
const defaultProps = {
  // 子节点的属性名称
  children: 'children',
  label: 'name',
}
// 页面加载时触发
onMounted(() => {
  getHasRole()
})
// 获取全部职位信息的方法
const getHasRole = async (pager = 1) => {
  pageNo.value = pager
  let result: any = await reqAllRoleList(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code === 200) {
    total.value = result.total
    allRole.value = result.data
  }
}
// 分页条数改变时触发
const sizeChange = () => {
  getHasRole()
}
// 搜索触发
const search = () => {
  getHasRole()
  keyword.value = ''
}
// 重置触发
let settingStore = useLayOutSettingStore()
const reset = () => {
  settingStore.refresh = !settingStore.refresh
}
// 校验
const validatorRoleName = (_role: any, value: any, callback: any) => {
  if (value.trim().length >= 2) {
    callback()
  } else {
    callback(new Error('请输入2个字符以上'))
  }
}
const rules = {
  roleName: [{ required: true, trigger: 'blur', validator: validatorRoleName }],
}
// 添加职位
const addRole = () => {
  // 打开弹窗
  dialogVisite.value = true
  // 清空表单数据
  Object.assign(RoleParams, { roleName: '', id: 0 })
  //清空校验
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}
// 编辑职位
const updateRole = (row: RoleData) => {
  // 打开弹窗
  dialogVisite.value = true
  // 存储已有的职位
  Object.assign(RoleParams, row)
  nextTick(() => {
    form.value.clearValidate('roleName')
  })
}

// 添加职位|编辑职位确定按钮回调
const save = async () => {
  await form.value.validate()
  let result: any = await reqAddOrUpdateRole(RoleParams)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: RoleParams.id ? '更新成功' : '添加成功',
    })
    dialogVisite.value = false
    getHasRole(RoleParams.id ? pageNo.value : 1)
  } else {
    ElMessage({
      type: 'error',
      message: RoleParams.id ? '更新失败' : '添加失败',
    })
    dialogVisite.value = false
    getHasRole(RoleParams.id ? pageNo.value : 1)
  }
}
// 删除职位
const deleteRole = async (id: number) => {
  let result: any = await reqRemoveRole(id)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasRole(allRole.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
// 显示已有的职位数据
const setPermission = async (row: RoleData) => {
  selectArr.value = []
  // 抽屉显示
  drawer.value = true
  // 收集当前要分类权限的职位的数据
  Object.assign(RoleParams, row)
  // 获取当前职位的权限数据
  let result: any = await reqAllMenuList(RoleParams.id as number)
  if (result.code == 200) {
    menuArr.value = result.data
    // selectArr.value = filterSelectArr(menuArr.value, [])
    selectArr.value = filterSelectArr(result.select, [])
  }
}
// 过滤已有的职位数据
const filterSelectArr = (allData: any, initArr: any) => {
  // 遍历allData数组
  allData.forEach((item: any) => {
    // 如果item有children属性，并且item的children数组长度大于0
    if (item.children && item.children.length > 0) {
      // 递归调用filterSelectArr函数，传入item的children数组和initArr数组
      filterSelectArr(item.children, initArr)
    } else {
      initArr.push(item.id)
    }
  })
  // 返回initArr数组
  return initArr
}
const formatDate = (isoString: any) => {
  try {
    const date = new Date(isoString)
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    const hours = date.getHours().toString().padStart(2, '0')
    const minutes = date.getMinutes().toString().padStart(2, '0')
    const seconds = date.getSeconds().toString().padStart(2, '0')

    // 构建格式化的日期字符串
    const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    return formattedDate
  } catch (error) {
    console.error('Invalid date format:', error)
    return null
  }
}
const createTimeformatter = (row: any) => {
  return formatDate(row.createTime)
}
const updateTimeformatter = (row: any) => {
  return formatDate(row.updateTime)
}

//编辑职位权限

const handler = async () => {
  // 职位ID
  const roleId = RoleParams.id as number
  let arr = tree.value.getCheckedKeys()
  let arr1 = tree.value.getHalfCheckedKeys()
  let permissionId = arr.concat(arr1)

  // 下发权限
  let result: any = await reqSetPermission(roleId, permissionId)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '权限设置成功',
    })
    drawer.value = false
    reset()
  } else {
    ElMessage({
      type: 'error',
      message: '权限设置失败',
    })
  }
}
</script>

<style lang="scss" scoped></style>
